package com.swgk.core.base.model.factory;

import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.orhanobut.logger.Logger;
import com.swgk.core.BuildConfig;
import com.swgk.core.base.api.AESUtils;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.swgk.core.util.MLog;

import org.json.JSONObject;
import org.jsoup.Connection;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Description:
 * Author zhengkewen
 * Time 2017/12/11
 */
public class CryptoResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private final TypeAdapter<T> adapter;
    private final Gson gson;

    CryptoResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        return parseBody(value);
    }

    /**
     * 统一对返回值处理
     * @param value
     * @return
     */
    private T parseBody(ResponseBody value) throws IOException{
        String result = value.string();
        //当data为数组格式，后台返回null时，添加一个空数组
        result = setDataListDeft(result);
        return adapter.fromJson(result);
    }

    /**
     * 处理 当data需要为数组，后台返回null时，在此处添加一个空数组
     * @param result
     * @return
     * @throws IOException
     */
    private String setDataListDeft(String result) throws IOException{
        BaseEntity baseEntity = (BaseEntity)adapter.fromJson(result);
        //当是数组，并且返回为空，创建一个空数组
        if (baseEntity != null && baseEntity.getData() instanceof ListResponse){
            if (baseEntity.getData() == null){
                baseEntity.setData(new ListResponse());
                result = gson.toJson(baseEntity);
            }
        }
        return result;
    }
}
